using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Library_management_system
{
    public partial class BorrowForm : Form
    {
        private string currentUsername;
        private int currentReaderId;

        public BorrowForm(string username)
        {
            InitializeComponent();
            currentUsername = username;
            currentReaderId = GetReaderId(username);
            LoadBooks();
        }

        private int GetReaderId(string username)
        {
            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = "SELECT ReaderID FROM Users WHERE Username=@username";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@username", username);
                object result = cmd.ExecuteScalar();
                return (result != null && result != DBNull.Value) ? Convert.ToInt32(result) : -1;
            }
        }

        private void LoadBooks(string keyword = "")
        {
            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = "SELECT BookID, Title, Author, Publisher, ISBN, PublishDate, Category, AvailableCount FROM Books WHERE AvailableCount > 0";
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    sql += " AND (Title LIKE @kw OR Author LIKE @kw OR ISBN LIKE @kw OR Category LIKE @kw)";
                }
                SqlCommand cmd = new SqlCommand(sql, conn);
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    cmd.Parameters.AddWithValue("@kw", "%" + keyword + "%");
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dgvBooks.DataSource = dt;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            LoadBooks(txtSearch.Text.Trim());
        }

        private void btnBorrow_Click(object sender, EventArgs e)
        {
            if (currentReaderId == -1)
            {
                MessageBox.Show("当前账号未绑定读者信息，无法借书！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (dgvBooks.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要借阅的图书！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int bookId = Convert.ToInt32(dgvBooks.SelectedRows[0].Cells["BookID"].Value);

            if (MessageBox.Show("确定要借阅该图书吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                using (SqlConnection conn = DatabaseConfig.GetConnection())
                {
                    conn.Open();
                    // 开启事务
                    SqlTransaction transaction = conn.BeginTransaction();
                    try
                    {
                        // 1. 插入借阅记录
                        string sqlInsert = "INSERT INTO BorrowRecords (BookID, ReaderID, BorrowDate, DueDate) VALUES (@BookID, @ReaderID, @BorrowDate, @DueDate)";
                        SqlCommand cmdInsert = new SqlCommand(sqlInsert, conn, transaction);
                        cmdInsert.Parameters.AddWithValue("@BookID", bookId);
                        cmdInsert.Parameters.AddWithValue("@ReaderID", currentReaderId);
                        cmdInsert.Parameters.AddWithValue("@BorrowDate", DateTime.Now);
                        cmdInsert.Parameters.AddWithValue("@DueDate", DateTime.Now.AddDays(30));
                        cmdInsert.ExecuteNonQuery();

                        // 2. 更新图书可借数量
                        string sqlUpdate = "UPDATE Books SET AvailableCount = AvailableCount - 1 WHERE BookID=@BookID";
                        SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, conn, transaction);
                        cmdUpdate.Parameters.AddWithValue("@BookID", bookId);
                        cmdUpdate.ExecuteNonQuery();

                        transaction.Commit();
                        MessageBox.Show("借阅成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        MessageBox.Show("借阅失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                LoadBooks(); // 刷新图书列表
            }
        }
    }
}